package Dao;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class YanZhengCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");resp.setContentType("text/plain;charset=utf8");
        //验证cookie
        boolean have_cookie=is_have_Cookie(req);
        if(have_cookie){
            System.out.println("Cookie验证成功");
            resp.sendRedirect("shopping.jsp");
        }
        else{
            System.out.println("Cookie验证失败");
            resp.sendRedirect("login.html");
        }
    }
    protected boolean is_have_Cookie(HttpServletRequest req){
        boolean have_cookie=false;
        Cookie[] cookies=req.getCookies();
        if(cookies!=null){
            System.out.println("--------------登录时cookie属性，并验证cookie------------");
            for(Cookie cookie:cookies){
                System.out.println(cookie.getName()+cookie.getValue());
            }
            for(Cookie cookie:cookies){
                if("right_login".equals(cookie.getName())){
                    have_cookie=true;
                    HttpSession httpSession=req.getSession();
                    httpSession.setAttribute("name",cookie.getValue());
                }
            }
        }
        return have_cookie;
    }
}
